const e = require("express");
const _hun = require("../import");

/**
 * @api {post} /sys/login  login
 * @apiDescription  用户登录的接口，注意用户登录成功后会在result中包含token参数，请前端本地保存token。
 * @apiName login
 * @apiGroup sys
 * @apiParam {string} name 用户名
 * @apiParam {string} pwd  用户密码
 * @apiSuccessExample {json} 请求成功的返回:
 *  {
 *      "status" : 200,
 *      "message" : "请求成功"
 *      "result" : "asjXzXxmnSp8TZGWiTSlJF8Gb...5LhYoHs86SEI2LBXrTZ9e/a4frZOWHZ"
 *  }
 * @apiErrorExample {json} 请求失败的返回
 * {
 *   "status": 404,
 *   "message" : "请求错误"
 *   "result": null
 * }
 * @apiSampleRequest http://127.0.0.1:9090/sys/login
 * @apiVersion 1.0.0
 */
 _hun.router.post('/login', async function (req, res) {
  var username = req.body.name,
      userpwd = req.body.pwd;

  var data = await _hun.db.query({
      sql: _hun.config.sql.userLogin,
      data: [username, _hun.utils.crypt(userpwd) ]
  })

    if (data.length != 0 ){
      var token = _hun.jwt.sign({
          id: data[0].user_id,
          username: data[0].user_name 
      }, _hun.config.jwt, { 
        expiresIn: 60*60*24 //token(24)生效时间
      });
      res.json({
          status: 200,
          message: '登录成功',
          result: {
            token: token
          }
      });
    } else {
      res.json({
          status: 404,
          message: '账户名或密码有误',
          result: null
      });
    }

});

/**
 * @api {post} /sys/add  add
 * @apiDescription  用户注册的接口
 * @apiName add
 * @apiGroup sys
 * @apiParam {string} name 用户名
 * @apiParam {string} pwd  用户密码
 * @apiParam {string} phone  用户手机号
 * @apiSuccessExample {json} 请求成功的返回:
 *  {
 *      "status" : 200,
 *      "message" : "注册成功"
 *      "result" : "asjXzXxmnSp8TZGWiTSlJF8Gb...5LhYoHs86SEI2LBXrTZ9e/a4frZOWHZ"
 *  }
 * @apiErrorExample {json} 请求失败的返回
 * {
 *   "status": 404,
 *   "message" : "注册失败"
 *   "result": null
 * }
 * @apiSampleRequest http://127.0.0.1:9090/sys/add
 * @apiVersion 1.0.0
 */

 _hun.router.post('/add', async function (req, res, next) {
    let username = req.body.name,
        userpwd = req.body.pwd,
        userphone = req.body.phone;    
    var pool = _hun.pool();
    let params = [username, _hun.utils.crypt(userpwd), userphone, _hun.utils.getTime()];
    pool.getConnection(function (err, conn) {
        if (err) {
          res.status(400).json({ status: '-200', message: '数据库连接失败' });
          return;
        }
        conn.query(_hun.config.sql.addUser, params, function (err, rs) {
            if (err) {
                if(err.message.includes('Duplicate')){
                    res.json({ 
                        status: '-200', 
                        message: '注册用户出错:用户名重复' 
                    });
                    return;
                }else{
                    res.json({ 
                        status: '-200', 
                        message: '注册用户出错:' + err.message 
                    });
                    return;
                }
            }
            res.json({
                status: 200,
                message: '注册成功',
                result: {}
            });
        });
        conn.release();
    });
});

module.exports = _hun.router;

/**
 * @api {post} /sys/userInfo  info
 * @apiDescription 获取用户的详情接口
 * @apiName info
 * @apiGroup Home
 * @apiParam {number} id 用户，从 /sys/index 接口中获得 id 作为id参数传入即可
 * @apiSuccessExample {json} 请求成功的返回:
 *  {
 *      "status" : 200,
 *      "message" : "请求成功"
 *      "result" : "asjXzXxmnSp8TZGWiTSlJF8Gb...5LhYoHs86SEI2LBXrTZ9e/a4frZOWHZ"
 *  }
 * @apiErrorExample {json} 请求失败的返回
 * {
 *   "status": 404,
 *   "message" : "请求失败"
 *   "result": null
 * }
 * @apiSampleRequest http://127.0.0.1:9090/sys/info
 * @apiVersion 1.0.0
 */
_hun.router.post('/getUserInfo', async function (req, res, next) {
    let data = await _hun.db.query({
        sql: _hun.config.sql.getUserInfo,
        data: [ _hun.jwt.decode(req.headers.authorizations).id]
    });
    if(data.length != 0) {
        res.json({
          status: 200,
          message: '用户详情获取成功',
          data: {
            id: data[0].user_id,
            name: data[0].name,
            phone: data[0].phone,
            type: data[0].user_type,
            address: data[0].address,
            headerimg: data[0].user_pic,
            money: data[0].user_money,
          }
        });
    } else {
        res.json({
          status: 200,
          message: '用户详情获取失败',
          result: {
          }
        });
    }
});
